import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

// 路由规则
const routes = [
    {
        path: '/',
        name: 'main',
        component: () => import('@/view/Main'),
        redirect: '/home',
        children: []
    },
    {
        path:'/login',
        name:'login',
        component: () => import('@/view/Login')
    }
]

const router = new VueRouter({
    routes
})

import cookie from 'js-cookie'
// 全局前置路由
router.beforeEach((to, from, next) => {
    // console.log("to",to)
    // console.log("from",from)
    const token = store.state.userOptions.token || cookie.get('token')
    if(to.name != 'login'){
        if(token == '' || token == undefined){
            next({name:'login'})
        }else{
            next()
            // let routerLength = router.options.routes.length
            // let baseInfostr = sessionStorage.getItem('baseinfo')
            // let baseInfo = JSON.parse(baseInfostr)
            // // baseInfo.forEach(element => {
            // //     router.addRouters('main',element)
            // // });
            // router.addRouters('main',baseInfo)
        }
    }else{
        next()
    }
})

// 避免重复路由
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

export default router